﻿namespace ufida.u9.ait.openapi
{
	using System;
	using System.Collections.Generic;
	using System.Text;
    using ufida.u9.ait.openapi.utils;
    using UFIDA.U9.Base;
    using UFIDA.U9.Base.Organization;
    using UFIDA.U9.CBO.Pub.Controller;
    using UFIDA.U9.CBO.SCM.Item;
    using UFIDA.U9.CBO.SCM.Warehouse;
    using UFIDA.U9.Complete.CompleteRpt;
    using UFIDA.U9.Complete.Enums;
    using UFIDA.U9.MO.Enums;
    using UFIDA.U9.MO.MO;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.Business;
    using UFSoft.UBF.Util.Context;

	/// <summary>
	/// CompleteApplySaveSV partial 
	/// </summary>	
	public partial class CompleteApplySaveSV 
	{	
		internal BaseStrategy Select()
		{
			return new CompleteApplySaveSVImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class CompleteApplySaveSVImpementStrategy : BaseStrategy
	{
		public CompleteApplySaveSVImpementStrategy() { }

		public override object Do(object obj)
		{						
			CompleteApplySaveSV bpObj = (CompleteApplySaveSV)obj;

			try
			{
				if (bpObj.Data == null || bpObj.Data.Count == 0)
					throw new Exception("传入参数为空");

				List<CommonArchiveDataDTOData> retlist = new List<CommonArchiveDataDTOData>();
				//List<object> inputdtos = DTOUtils.DTOListPropCopy(bpObj.Data.ConvertAll(item => item as object)
				//	, typeof(CopyOfDepartmentDTOData));
				foreach (var dto in bpObj.Data)
				{
					CompleteApplyDoc item = CompleteApplyDoc.Finder.Find($"DocNo='{dto.DocNo}'");
					if (item == null)
					{
                        //新增逻辑
                        CompleteApplyDoc doc = CreateDoc(dto);
						doc=ApproveDoc(doc);
						CommonArchiveDataDTOData ret = new CommonArchiveDataDTOData()
						{
							ID = doc.ID,
							Code = doc.DocNo,
						};
						retlist.Add(ret);
					}
					else
					{
						//修改逻辑
						throw new AITException(599,$"单号:{dto.DocNo}已经存在,不能生成!");
					}
				}
				return ResultUtils.success(bpObj, bpObj.Data, retlist);
			}
			catch (Exception ex)
			{
				return ResultUtils.error(bpObj, bpObj.Data, ex);
			}
		}

		private CompleteApplyDoc CreateDoc(CompleteApplyDTOData dto)
        {
			CompleteApplyDoc item;

			//创建单据
			using (ISession se = Session.Open())
			{
				item = CompleteApplyDoc.Create();
				item.SourceDoc = new UFIDA.U9.MO.PropertyTypes.MOSourceDoc()
				{
					MOSrcDocType = MOSrcDocTypeEnum.MO,
				};
				item.DocNo = dto.DocNo;
				item.Org = EntityUtils.GetEntityByCode<Organization>(dto.Org.Code);
				item.CompleteApplyDocType = EntityUtils.GetEntityByCode<CompleteApplyDocType>(dto.CompleteApplyDocType.Code);
				item.BusinessDate = DateTime.Parse(dto.BusinessDate);
				item.ApplyDate = DateTime.Parse(dto.ApplyDate);
				item.DocState = CompleteApplyDocStatusEnum.Opened;
				item.CompleteApplyDocLines = new CompleteApplyDocLine.EntityList();

				int i = 0;
				foreach (var linedto in dto.CompleteApplyLines)
				{
					//校验
					if (linedto.Item == null)
						throw new Exception("必须传入物料[Item]");

					MO mo = EntityUtils.GetDocEntity<MO>(linedto.MO.Code);
					if(mo.ItemMaster.Code!=linedto.Item.Code)
						throw new Exception($"来源物料[{mo.ItemMaster.Code}]与传入物料[{linedto.Item.Code}]不同");

					//赋值
					i++;
					CompleteApplyDocLine line = CompleteApplyDocLine.Create();
					line.Item = EntityUtils.GetEntityByCode<ItemMaster>(linedto.Item.Code);
					line.PUToPBURate = 1;
					line.ProductUOM = line.Item.ManufactureUOM;
					line.ProductBaseUOM = line.Item.ManufactureUOM.BaseUOM;
					line.PerformingOrg = item.Org;
					line.PBUToCBURate = 1;
					line.OperationState = TargetOpStateEnum.Transferring;
					line.MO = mo;
					line.LineNum = i * 10;
					line.EligibleQtyCoUOM = linedto.CompleteQty;
					line.EligibleQty = linedto.CompleteQty;
					line.CUToCBURate = 1;
					line.CoUOM = line.Item.ManufactureUOM;
					line.CostBaseUOM = line.Item.ManufactureUOM.BaseUOM;
					line.CompleteWh = EntityUtils.GetEntityByCode<Warehouse>(linedto.CompleteWh.Code);
					line.CompleteQtyCoUOM = linedto.CompleteQty;
					line.CompleteQty = linedto.CompleteQty;
					line.CompleteDate = DateTime.Parse(linedto.CompleteDate);
					line.CompleteApplyDoc = item;

					item.CompleteApplyDocLines.Add(line);
				}
				se.Commit();
			}

			//修改单号
			using(ISession se = Session.Open())
            {
				item.DocNo = dto.DocNo;
				se.Commit();
            }

			return item;
		}

		private CompleteApplyDoc ApproveDoc(CompleteApplyDoc be)
        {
			using(ISession se = Session.Open())
            {
				be.DocState = CompleteApplyDocStatusEnum.Approved;
				be.ApproveBy = Context.LoginUser;
				be.ApproveOn=DateTime.Now;

				se.Commit();
			}
			return be;
        }
	}

	#endregion
	
	
}